package root.electronclass.electronclass

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.appcompat.app.ActionBar
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.SPUtils
import root.electronclass.electronclass.common.base.CommonDialogFragment
import root.electronclass.electronclass.common.base.ViewBindingActivity
import root.electronclass.electronclass.common.event.NetWorkEvent
import root.electronclass.electronclass.common.event.PersonSuccess
import root.electronclass.electronclass.common.util.DateUtils
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.VersionData
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.adapter.FragmentTabAdapter
import root.electronclass.electronclass.application.ApplicationFragment
import root.electronclass.electronclass.common.util.DeviceType
import root.electronclass.electronclass.databinding.ActivityMain2Binding
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.grade.model.PersonType
import root.electronclass.electronclass.other.AttestationActivity
import root.electronclass.electronclass.other.EntryFaceActivity
import root.electronclass.electronclass.other.NetworkChangeReceiver
import root.electronclass.electronclass.other.SetBgActivity
import root.electronclass.electronclass.other.dialog.SetDialog
import root.electronclass.electronclass.personal.PersonalFragment
import root.electronclass.electronclass.personal.dialog.TipsDialog
import root.electronclass.electronclass.school.SchoolFragment2
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.entity.CampusPoint
import root.electronclass.electronclass.mvp.entity.EcardInfo
import root.electronclass.electronclass.mvp.rest.ClassApi
import com.hikvision.dmb.system.InfoSystemApi
import com.hikvision.dmb.time.InfoTimeApi
import com.hikvision.dmb.util.InfoUtilApi
import com.hikvision.smarteyes.smartdev.FaceSdk
import com.jackwang.updateapk.UpdateApp
import com.jackwang.updateapk.UpdateListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Response
import java.io.File
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class MainActivity2 : ViewBindingActivity<ActivityMain2Binding>() {
    private val SET = 1000
    private val ATTESTATION = 1001
    private val COUNTS = 4 // 点击次数
    private val DURATION: Long = 1000 // 规定有效时间
    private var mHits = LongArray(COUNTS)
    private var fragmentTabAdapter: FragmentTabAdapter? = null
    private var dialog: Dialog? = null
    private var startDialogTv: TextView? = null
    private var startDialogPro: TextView? = null
    private var networkChangeReceiver = NetworkChangeReceiver()

    private val fragments: ArrayList<Fragment?> = object : ArrayList<Fragment?>() {
        init {
            add(ApplicationFragment())//应用中心
            add(SchoolFragment2())//校园中心
            add(PersonalFragment())//个人中心
        }
    }

    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetWorkEvent(event: NetWorkEvent) {
        if (!event.connect) {
            TipsDialog().also {
                it.arguments = bundleOf(
                    CommonDialogFragment.TITLE to "温馨提示",
                    CommonDialogFragment.CLOSE to true
                )
            }.show(supportFragmentManager, "TIPS")
        }
    }


    override fun init() {
        binding.top.setup(lifecycle, null,false)
        SPUtils.getInstance().put("runResult", false)
        binding.top.title.visibility = View.GONE

        val filter = IntentFilter()
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(networkChangeReceiver, filter)
        initFragment()
        binding.setIv.setOnClickListener {
            startActivityForResult(Intent(this@MainActivity2, SetBgActivity::class.java), SET)
        }
        /**
         * 人脸SDK初始化，使用人脸功能前必须调用初始化。
         * 初始化需要放到MainActivity中，
         */
        /**
         * 人脸SDK初始化，使用人脸功能前必须调用初始化。
         * 初始化需要放到MainActivity中，
         */
        FaceSdk.get().init(this)
        setSystem()
        binding.top.schoolIcon.setOnClickListener {
            continuousClick(true)
        }

        binding.face.setOnClickListener {
            startActivity(Intent(this@MainActivity2, EntryFaceActivity::class.java))
        }
        binding.attendance.setOnClickListener {
            val intent = Intent(this@MainActivity2, AttestationActivity::class.java)
            intent.putExtra("RequestCode", AttestationActivity.ATTENDANCE)
            startActivityForResult(intent, AttestationActivity.ATTENDANCE)
        }
        binding.scanIv.setOnClickListener {
            binding.scanCl.isVisible = !binding.scanCl.isVisible
        }
        initDialog()
        if (GlobalParameter.getEcardInfo().type == 5) {
            setKESystem()
            binding.face.isVisible = false
        } else {
            setHKSystem()
        }
        downApk()
        campusPoint()
        runResult()
        cycleSetTime()
    }


    private fun runResult() {
        lifecycle.coroutineScope.launch(CoroutineExceptionHandler()) {
            delay(10000)
            SPUtils.getInstance().put("runResult", true)
        }
    }

    private fun campusPoint() {
        RestManager.getInstance().initRest().campusPoint().enqueue(object : CallbackNext<BaseResponse<List<CampusPoint>>>(mDialogViewModel){
            override fun onSuccessful(call: Call<BaseResponse<List<CampusPoint>>>?, response: BaseResponse<List<CampusPoint>>) {
                if (response.rows != null && response.rows.size > 0 && response.rows[0].qrCodePicFormat != null && response.rows[0].qrCodePicFormat.size > 0) {
                    binding.scanIv.visibility = View.VISIBLE
                    binding.scan.setImageURI(response.rows[0].qrCodePicFormat[0].url)
                }

            }

            override fun onError(call: Call<BaseResponse<List<CampusPoint>>>?, response: BaseResponse<List<CampusPoint>>?) {

            }

        })
    }

    private fun initDialog() {
        val view: View = (getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(R.layout.download_dialog, null)
        dialog = Dialog(this@MainActivity2, R.style.CustomDialog)
        dialog!!.addContentView(view, ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT))
        startDialogTv = view.findViewById(R.id.start_tv)
        startDialogPro = view.findViewById(R.id.progress_tv)
    }


    private fun setSystem() {
        //设置默认 Launcher 设置 Launcher 后，效果即时生效，但是系统需要 10s+保存配置保证重启后 仍为设置的 Launcher 应用
        InfoSystemApi.setLauncherForced("root.electronclass.electronclass")
        //系统保护程序使能
        InfoUtilApi.addProtection("root.electronclass.electronclass", "root.electronclass.electronclass", true, "root.electronclass.electronclass.other.DeviceCodeActivity", "")
        InfoUtilApi.enableProtection("root.electronclass.electronclass", true)
        //设置定时开关机
        if (GlobalParameter.getEcardInfo().powerTime.powerOffTime.orEmpty().isNotEmpty()) {
            val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            var dateOnTime: Date? = null
            var dateOffTime: Date? = null
            try {
                dateOffTime = sdf.parse(DateUtils.getNowDate(DateUtils.DatePattern.ONLY_DAY) + " " + GlobalParameter.getEcardInfo().powerTime.powerOffTime)
                dateOnTime = sdf.parse(DateUtils.tomorrow()+ " "+ GlobalParameter.getEcardInfo().powerTime.powerOnTime)
            } catch (e: ParseException) {
                e.printStackTrace();
            }
            InfoTimeApi.setTimeSwitch(dateOffTime!!.time, dateOnTime!!.time)
        }
        InfoSystemApi.openAdb()


    }



    /**
     * logo连点判断
     */
    private fun continuousClick(b: Boolean) {
        //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
        //为数组最后一位赋值
        mHits[mHits.size - 1] = SystemClock.uptimeMillis()
        if (mHits[0] >= SystemClock.uptimeMillis() - DURATION) {
            mHits = LongArray(COUNTS) //重新初始化数组
            if (b) {
                SetDialog().also {
                    it.arguments = bundleOf(
                        CommonDialogFragment.TITLE to "班牌登陆",
                        CommonDialogFragment.CLOSE to true,
                        CommonDialogFragment.CANCEL to "取消",
                        CommonDialogFragment.OK to "确定"
                    )
                }.show(supportFragmentManager, "SET")
            }
        }
    }

    /**
     * 静默安装应用
     */
    private fun silentInstallation() {
        InfoUtilApi.silentInstallation("")
    }



    private fun setHKSystem() { //设置默认 Launcher 设置 Launcher 后，效果即时生效，但是系统需要 10s+保存配置保证重启后 仍为设置的 Launcher 应用
        InfoSystemApi.setLauncherForced("root.electronclass.electronclass") //系统保护程序使能
        InfoUtilApi.addProtection(
            "root.electronclass.electronclass", "root.electronclass.electronclass", true,
            "root.electronclass.electronclass.currency.LauncherActivity", ""
        )
        InfoUtilApi.enableProtection("root.electronclass.electronclass", true) //设置定时开关机
        DeviceType.HK_OFF_ON()
        /**
         * 人脸SDK初始化，使用人脸功能前必须调用初始化。
         * 初始化需要放到MainActivity中，
         */
        FaceSdk.get().init(this)
    }

    private fun setKESystem() {
        DeviceType.KE_OFF_ON(this@MainActivity2)
    }

    private var portion = 1
    private fun initFragment() {

        fragmentTabAdapter = FragmentTabAdapter(this, fragments, R.id.frameLayout, findViewById(R.id.radioGroup), portion)
        fragmentTabAdapter?.onRgsExtraCheckedChangedListener =
            object : FragmentTabAdapter.OnRgsExtraCheckedChangedListener() {
                override fun OnRgsExtraCheckedChanged(
                    radioGroup: RadioGroup?,
                    checkedId: Int,
                    index: Int
                ) {
                    when (index) {

                        0 -> {
                            portion = index
                            binding.top.setup(lifecycle, "应用中心")
                        }
                        1 -> {
                            portion = index
                        }
                        2 -> {
                            binding.top.setup(lifecycle, "个人空间")
                            val intent = Intent(this@MainActivity2, AttestationActivity::class.java)
                            startActivityForResult(intent, AttestationActivity.personal)
                        }

                    }
                }
            }
    }

    private fun downApk() {
        RestManager.getInstance().initRest().version()
                .enqueue(object : CallbackNext<BaseResponse<VersionData>>(mDialogViewModel) {
                    override fun onSuccessful(
                        call: Call<BaseResponse<VersionData>>?,
                        response: BaseResponse<VersionData>,
                    ) {
                        if (response.isSuccess && getVersionCode(this@MainActivity2) < response.rows.version.toInt() &&
                                !response.rows.pkgUrl.isNullOrEmpty()) {
                            UpdateApp.getInstance().setAutoInatall(false) //是否弹起安装apk
                                    .setUpdateListener(object : UpdateListener {
                                        override fun start() {
                                            startDialogTv?.text = "开始下载"
                                            dialog?.show()
                                        }

                                        override fun progress(progress: Int) {
                                            if (dialog != null) {
                                                startDialogPro?.text = "进度：$progress"
                                            }
                                        }

                                        override fun downFinish() {
                                            if (dialog != null) {
                                                startDialogTv?.text = "下载完成"
                                                dialog?.dismiss()
                                                val path = Environment.getExternalStorageDirectory()
                                                        .toString() + File.separator + "download/app.apk"
                                                Log.i("MainActivity", "downFinish: $path")
                                                if (GlobalParameter.getEcardInfo().type == 5) {
                                                    UpdateApp.getInstance().startInstall(this@MainActivity2)
                                                } else {
                                                    InfoUtilApi.silentInstallation(path)
                                                }
                                            }
                                        }

                                        override fun downFail(throwable: Throwable) {
                                            ToastUtil.showToast(
                                                    this@MainActivity2,
                                                    "下载失败：" + throwable.message
                                            )
                                            if (dialog != null) {
                                                dialog?.dismiss()
                                            }
                                        }
                                    }).downloadApp(
                                            this@MainActivity2,
                                            response.rows.pkgUrl,
                                            R.mipmap.ic_launcher,
                                            R.mipmap.ic_launcher
                                    )
                        }
                    }

                    override fun onError(
                        call: Call<BaseResponse<VersionData>>,
                        response: BaseResponse<VersionData>?,
                    ) {
                        toast(response?.msg)
                    }

                })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SET) {
                setWindowBackGround()
            } else if (requestCode == AttestationActivity.personal) {
                val result: Boolean = data?.getBooleanExtra("SUCCESS", false) as Boolean
                if (result) {
                    lifecycleScope.launch(CoroutineExceptionHandler { }) {
                        val result = withContext(Dispatchers.IO) { ClassApi.service.login() }
                        if (result != null && result.isSuccess) {
                            if (result.rows.personType == PersonType.TEACHER) {
                                TipsDialog().also {
                                    it.arguments = bundleOf(
                                        CommonDialogFragment.TITLE to "温馨提示",
                                        TipsDialog.DATA to "个人空间仅针对学生开发，教职工个人信息请通过手机查看",
                                        CommonDialogFragment.CLOSE to true
                                    )
                                }.show(supportFragmentManager, "PERSON")
                                findViewById<RadioButton>(binding.radioGroup.getChildAt(portion).id).isChecked = true
                            } else {
                                portion = 3
                                EventBus.getDefault().post(PersonSuccess())
                            }
                        }
                    }

                } else {
                    findViewById<RadioButton>(binding.radioGroup.getChildAt(portion).id).isChecked = true
                }
            }
        }
    }

    private val handler = Handler(Looper.getMainLooper())
    private val interval: Long = 2 * 60 * 60 * 1000 // 2 小时的毫秒数
    private val runnable = object : Runnable {
        override fun run() {
            // 在这里执行你的操作
            executeTask()

            // 继续下一次
            handler.postDelayed(this, interval)
        }
    }

    private fun cycleSetTime() {
        handler.postDelayed(runnable, interval)
    }

    private fun executeTask() {
        RestManager.getInstance().initRest().getElectorInfo(GlobalParameter.getDeviceCode())
            .enqueue(object : CallbackNext<BaseResponse<EcardInfo>>(mDialogViewModel) {

                override fun onSuccessful(call: Call<BaseResponse<EcardInfo>>,
                                          response: BaseResponse<EcardInfo>,
                ) {
                    if (response.isSuccess) {
                        GlobalParameter.setEcardInfo(response.rows)
                        if (GlobalParameter.getEcardInfo().type == 5) {
                            setKESystem()
                        } else {
                            DeviceType.HK_OFF_ON()
                        }
                    }
                }

                override fun onError(
                    call: Call<BaseResponse<EcardInfo>>,
                    response: BaseResponse<EcardInfo>,
                ) {
                }

                override fun onFail(
                    call: Call<BaseResponse<EcardInfo>>?,
                    t: Throwable?,
                    response: Response<BaseResponse<EcardInfo>>?,
                ) {
                }

            })
    }



    override fun onDestroy() {
        super.onDestroy()
        /**
         * 应用退出时，需要释放人脸SDK模块内部资源，整个应用周期内不需要释放。
         * 如中途调用了释放，再次使用前需要先初始化。
         */
        FaceSdk.get().destroy()
        EventBus.getDefault().unregister(this)
        unregisterReceiver(networkChangeReceiver);
        handler.removeCallbacks(runnable)
    }


}